<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="领用单号" prop="batchNumber">
        <el-input v-model="queryParams.batchNumber" placeholder="请输入领用单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="领用主题" prop="outTheme">
        <el-input v-model="queryParams.outTheme" placeholder="请输入领用主题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划领用日期">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item label="领用状态" prop="outStatus">
        <el-select v-model="queryParams.outStatus" placeholder="请选择领用状态" clearable>
          <el-option v-for="dict in dict.type.out_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['elec:elecMaterialOutinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['elec:elecMaterialOutinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['elec:elecMaterialOutinfo:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="elecMaterialOutinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="outId" />
      <el-table-column label="领用单号" align="center" prop="batchNumber" />
      <el-table-column label="领用主题" align="center" prop="outTheme" />
      <el-table-column label="单据类别" align="center" prop="outType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.batch_type" :value="scope.row.outType" />
        </template>
      </el-table-column>
      <el-table-column label="计划领用日期" align="center" prop="planOutDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planOutDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用人" align="center" prop="outUserName" />
      <el-table-column label="领用状态" align="center" prop="outStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.out_status" :value="scope.row.outStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['elec:elecMaterialOutinfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['elec:elecMaterialOutinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工器具领用对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="领用单号" prop="batchNumber">
              <el-input v-model="form.batchNumber" :disabled="true" placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领用主题" prop="outTheme">
              <el-input v-model="form.outTheme" placeholder="请输入领用主题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划领用日期" prop="planOutDate">
              <el-date-picker clearable v-model="form.planOutDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择计划领用日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领用人" prop="outUserId">
              <el-select v-model="form.outUserId" filterable placeholder="请选择领用人">
                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddMaterial">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-delete" size="mini" @click="handleDelMaterial">移除</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="elecMaterialList" height="450" @selection-change="handleSelectionChangeMaterial">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="materialId" />
        <el-table-column label="工器具编码" align="center" prop="materialCode" width="100" />
        <el-table-column label="工器具名称" align="center" prop="materialName" width="200" />
        <el-table-column label="是否出库" align="center" prop="isOut">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.is_out" :value="scope.row.isOut" />
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" prop="sortName" width="100" />
        <el-table-column label="库房" align="center" prop="warehouseName" width="100" />
        <el-table-column label="柜架" align="center" prop="cabinetName" width="100" />
        <el-table-column label="层位" align="center" prop="gridName" width="100" />
        <el-table-column label="供应商" align="center" prop="providerName" width="100" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="selectTitle" :visible.sync="selectOpen" width="1000px" append-to-body>
      <el-form :model="queryMaterialParams" ref="queryMaterialForm" size="small" :inline="true" v-show="showSearch"
        label-width="100px">
        <el-form-item label="工器具编码" prop="materialCode">
          <el-input v-model="queryMaterialParams.materialCode" placeholder="请输入工器具编码" clearable @keyup.enter.native="handleMaterialQuery" />
        </el-form-item>
        <el-form-item label="工器具名称" prop="materialName">
          <el-input v-model="queryMaterialParams.materialName" placeholder="请输入工器具名称" clearable @keyup.enter.native="handleMaterialQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterialQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain size="mini" :disabled="multiple" @click="confirmMaterial">确认</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getMaterialList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="elecMaterialListSelect" @selection-change="handleSelectionChangeSelect">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="materialId" />
        <el-table-column label="工器具编码" align="center" prop="materialCode" width="100" />
        <el-table-column label="工器具名称" align="center" prop="materialName" width="200" />
        <el-table-column label="分类" align="center" prop="sortName" width="100" />
        <el-table-column label="库房" align="center" prop="warehouseName" width="100" />
        <el-table-column label="柜架" align="center" prop="cabinetName" width="100" />
        <el-table-column label="层位" align="center" prop="gridName" width="100" />
        <el-table-column label="供应商" align="center" prop="providerName" width="100" />
      </el-table>
      <pagination v-show="totalMaterial>0" :total="totalMaterial" :page.sync="queryMaterialParams.pageNum" :limit.sync="queryMaterialParams.pageSize"
        @pagination="getMaterialList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSelect">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="searchImgTitle" :visible.sync="searchImgOpen" width="700px">
      <el-descriptions title="刷脸信息">
        <el-descriptions-item label="设备">{{form.faceDeviceName}}</el-descriptions-item>
        <el-descriptions-item label="用户">{{form.faceUserName}}</el-descriptions-item>
        <el-descriptions-item label="刷脸时间">{{form.sendTime}}</el-descriptions-item>
      </el-descriptions>
      <img :src="form.facePicuture" :hidden="isHidden" width="650px" style="text-align: center;" />
    </el-dialog>
  </div>
</template>

<script>
  import {
    listElecMaterialOutinfo,
    getElecMaterialOutinfo,
    delElecMaterialOutinfo,
    addElecMaterialOutinfo,
    updateElecMaterialOutinfo,
    listUserOptions,
    listElecMaterial,
    searchImg
  } from "@/api/elec/elecMaterialOutinfo";
  import {
    jsonElecMaterialOutInfo
  } from "@/api/elec/downloadData";

  export default {
    name: "ElecMaterialOutinfo",
    dicts: ['out_status', 'batch_type', 'is_out'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        //日期控件
        dateRange: [],
        // 总条数
        total: 0,
        // 选择工器具列表总条数
        totalMaterial: 0,
        // 工器具领用表格数据
        elecMaterialOutinfoList: [],
        // 工器具表格数据
        elecMaterialList: [],
        // 选择工器具表格数据
        elecMaterialListSelect: [],
        // 选择工器具表格数据
        elecMaterialListTemp: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 弹出层标题（选择）
        selectTitle: "",
        // 是否显示弹出层（选择）
        selectOpen: false,
        // 弹出层标题（选择）
        searchImgTitle: "",
        // 是否显示弹出层（选择）
        searchImgOpen: false,
        // 是否隐藏
        isHidden: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          batchNumber: null,
          outTheme: null,
          planOutDate: null,
          outUserId: null,
          outStatus: null,
          materialCategory: "1",
          outIds: null
        },
        queryMaterialParams: {
          pageNum: 1,
          pageSize: 10,
          materialCode: null,
          materialName: null,
          materialStatus: 1,
          sortId: null,
          warehouseId: null,
          providerId: null,
          materialCategory: "1",
        },
        queryImgParams: {
          outId: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          outTheme: [{
            required: true,
            message: "领用主题不能为空",
            trigger: "blur"
          }],
          planOutDate: [{
            required: true,
            message: "计划领用日期不能为空",
            trigger: "blur"
          }],
          outUserId: [{
            required: true,
            message: "领用人不能为空",
            trigger: "change"
          }],
        },
        userOptions: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询工器具领用列表 */
      getList() {
        this.loading = true;
        listElecMaterialOutinfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.elecMaterialOutinfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          outId: null,
          batchNumber: null,
          outTheme: null,
          planOutDate: null,
          outUserId: null,
          materialCategory: null,
          outStatus: null,
          remark: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
        };
        this.elecMaterialList = [];
        this.elecMaterialListSelect = [];
        this.elecMaterialListTemp = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.outId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        listUserOptions().then(response => {
          this.userOptions = response.data;
        });
        this.open = true;
        this.title = "添加工器具领用";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        listUserOptions().then(response => {
          this.userOptions = response.data;
        });
        const outId = row.outId || this.ids
        getElecMaterialOutinfo(outId).then(response => {
          this.form = response.data;
          this.elecMaterialList = response.data.elecMaterialList;
          this.open = true;
          this.title = "修改工器具领用";
        });
      },
      searchImg(row) {
        this.reset();
        this.queryImgParams.outId = row.outId;
        searchImg(this.queryImgParams).then(response => {
          this.form = response.data;
          if (null != this.form.facePicuture && "" != this.form.facePicuture && undefined != this.form.facePicuture) {
            this.isHidden = false;
          }
          this.searchImgOpen = true;
          this.searchImgTitle = "查看刷脸记录";
        });
      },
      // 取消按钮
      cancelSelect() {
        this.selectOpen = false;
      },
      /** 查询工器具列表 */
      getMaterialList() {
        this.loading = true;
        listElecMaterial(this.queryMaterialParams).then(response => {
          this.elecMaterialListSelect = response.rows;
          this.totalMaterial = response.total;
          this.loading = false;
        });
      },
      // 多选框选中数据
      handleSelectionChangeMaterial(selection) {
        //选择时清空临时选中
        this.elecMaterialListTemp = [];
        let data = selection.map(item => item);
        for (let i = 0; i < data.length; i++) {
          this.elecMaterialListTemp.push(data[i]);
        }
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 搜索按钮操作 */
      handleMaterialQuery() {
        this.queryMaterialParams.pageNum = 1;
        this.getMaterialList();
      },
      /** 重置按钮操作 */
      resetMaterialQuery() {
        this.resetForm("queryMaterialForm");
        this.handleMaterialQuery();
      },
      /** 选择新增工器具按钮操作 */
      handleAddMaterial() {
        this.selectOpen = true;
        this.selectTitle = "选择工器具";
        this.getMaterialList()
      },
      handleDelMaterial() {
        let newData = this.elecMaterialList.filter((a) => !this.elecMaterialListTemp.some((b) => a.materialId === b.materialId));
        this.elecMaterialList = newData;
      },
      // 多选框选中数据
      handleSelectionChangeSelect(selection) {
        //选择时清空临时选中
        this.elecMaterialListTemp = [];
        let data = selection.map(item => item);
        for (let i = 0; i < data.length; i++) {
          this.elecMaterialListTemp.push(data[i]);
        }
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      confirmMaterial() {
        for (let i = 0; i < this.elecMaterialListTemp.length; i++) {
          this.elecMaterialList.push(this.elecMaterialListTemp[i]);
        }
        this.elecMaterialList = this.listRemoveRepeat(this.elecMaterialList);
        this.selectOpen = false;
      },
      //去重表格选择数据
      listRemoveRepeat(x) {
        let result = [];
        for (let i = 0; i < x.length; i++) {
          let flag = true;
          let temp = x[i];
          for (let j = 0; j < result.length; j++) {
            // 普通数组 (temp === result[j])
            if (temp.materialId === result[j].materialId) {
              flag = false;
              break;
            }
          }
          if (flag) {
            result.push(temp);
          }
        }
        return result;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.outId != null) {
              this.form.elecMaterialList = this.elecMaterialList;
              updateElecMaterialOutinfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.materialCategory = "1";
              this.form.elecMaterialList = this.elecMaterialList;
              addElecMaterialOutinfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const outIds = row.outId || this.ids;
        this.$modal.confirm('是否确认删除工器具领用编号为"' + outIds + '"的数据项？').then(function() {
          return delElecMaterialOutinfo(outIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('elec/elecMaterialOutinfo/export', {
          ...this.queryParams
        }, `elecMaterialOutinfo_${new Date().getTime()}.xlsx`)
      },
      //下载数据按钮
      downloadData() {
        if (this.ids.length == 0) {
          this.$confirm('此操作将下载所有文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            jsonElecMaterialOutInfo(this.queryParams).then(response => {
              if (response.code == 200) {
                this.$message({
                  message: `数据成功下载至${response.msg}中`,
                  type: 'success'
                });
              } else {
                this.$message.error('数据下载失败');
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消下载'
            });
          });
        } else {
          this.queryParams.outIds = JSON.parse(JSON.stringify(this.ids))
          jsonElecMaterialOutInfo(this.queryParams).then(response => {
            if (response.code == 200) {
              this.$message({
                message: `数据成功下载至${response.msg}中`,
                type: 'success'
              });
            } else {
              this.$message.error('数据下载失败');
            }
          })
        }
      },
    }
  };
</script>
